package baseclass.c_globalToPartMatrix;

/**
 * 从左到右，从上到下，旋转打印矩阵【要求】 额外空间复杂度为O(1)
 *
 * @date 2020/2/27 22:11
 */
public class Code01_PrintMatrix {
    public static void main(String[] args) {
//        int[][]m = {{1,2,3},{4,5,6},{7,8,9}};
//        int[][]m = {{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15}};
        int[][] m = {{1, 2, 3, 4, 0}, {5, 6, 7, 8, 0}, {9, 10, 11, 12, 0},
                {13, 14, 15, 16, 0}};
        spiralOrderPrint(m);
    }

    public static void spiralOrderPrint(int[][] matrix) {
        int a = 0;
        int b = 0;
        //矩阵的行数
        int c = matrix.length - 1;
        //矩阵的列数
        int d = matrix[0].length - 1;
        //左上角 始终不能超 右下角
        while (a <= c && b <= d) {
            print(matrix, a++, b++, c--, d--);
        }
    }
    public static void print(int[][] m, int a, int b, int c, int d) {
        //只有一行
        if(a == c){
            for (int i = b; i <= d ; i++) {
                System.out.println(m[a][i]);
            }
            return;
        }
        //只有一列
        if(b == d){
            for (int i = a; i <= c ; i++) {
                System.out.println(m[i][b]);
            }
            return;
        }
        int curCol = b;
        //从左到右
        for (; curCol < d; curCol++) {
            System.out.println(m[a][curCol]);
        }
        //从上到下
        int curRow = a;
        for (; curRow < c; curRow++) {
            System.out.println(m[curRow][d]);
        }
        //从右到左
        for (curCol = d; curCol > b; curCol--) {
            System.out.println(m[c][curCol]);
        }
        //从下到上
        for (curRow = c; curRow > a; curRow--) {
            System.out.println(m[curRow][b]);
        }
    }
}
